package com.jiejie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiejie.entity.Movie;
import com.jiejie.entity.Order;
import com.jiejie.mapper.MovieMapper;
import com.jiejie.mapper.OrderMapper;
import com.jiejie.service.OrderByService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderByServiceImpl implements OrderByService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MovieMapper movieMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Cacheable(cacheNames = "OrderBy_Movie",key = "'OrderByMovie'")
    @Override
    public LinkedHashMap<Movie, List<Object>> OrderBy() {
        System.out.println("该函数返回哈哈哈东方红饭店和");
        List<Order> orders = orderMapper.selectList(null);
        LinkedHashMap<Movie,List<Object>> map = new LinkedHashMap<>();
        //记录订单中每个电影出现的个数
        int [] movieIdArr = new int[100];
        for (int i=0;i<orders.size();i++){
            Integer movieId = orders.get(i).getMovieId();
            movieIdArr[movieId]++;
        }
        //循环遍历
        for (int j=0;j<movieIdArr.length;j++){
            if (movieIdArr[j] !=0){
                QueryWrapper wrapper = new QueryWrapper<>();
                wrapper.eq("movie_id",j);
                List<Order> orderList = orderMapper.selectList(wrapper);
                Movie movie = movieMapper.selectById(j);
                Double TotalPrice = 0.0;
                for (int n=0;n<orderList.size();n++){
                    String OrderPrice = orderList.get(n).getOrderAdjustedPrice().toString();
                    TotalPrice+= Double.parseDouble(OrderPrice);
                }
                List<Object> list = new ArrayList<>();
                list.add(orderList);
                list.add(TotalPrice);
                map.put(movie,list);
            }
        }

        System.out.println("======================================"+map);
        List<Map.Entry<Movie,List<Object>>> entryList = new ArrayList<>(map.entrySet());
        Collections.sort(entryList, new Comparator<Map.Entry<Movie, List<Object>>>() {
            @Override
            public int compare(Map.Entry<Movie, List<Object>> o1, Map.Entry<Movie, List<Object>> o2) {
                return (int) (Math.round(Double.parseDouble(o2.getValue().get(1).toString())) - Math.round(Double.parseDouble(o1.getValue().get(1).toString())));
            }
        });
        LinkedHashMap<Movie,List<Object>> listLinkedHashMap = new LinkedHashMap<>();
        for (Map.Entry<Movie,List<Object>> e:entryList
        ){
            listLinkedHashMap.put(e.getKey(),e.getValue());
        }
        return listLinkedHashMap;
    }
}
